# _*_ coding:utf-8
'''
利用向量实现方向移动
'''
import sys

import pygame
from pygame.locals import *

from vector import Vector2D

bgimg_str="../bgimg.jpg"
sprite_str="../mouseimg.png"
screen_width=700
screen_height=600

pygame.init()

screen=pygame.display.set_mode((screen_width,screen_height),0,32)
bgimg=pygame.image.load(bgimg_str).convert()
sprite=pygame.image.load(sprite_str).convert_alpha()

clock=pygame.time.Clock()
sprite_pos=Vector2D(screen_width/2-sprite.get_width()/2,screen_height/2-sprite.get_height()/2)
sprite_speed=100.

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()

    press_keys=pygame.key.get_pressed()
    # 方向向量
    key_direction=Vector2D(0,0)
    if press_keys[K_LEFT]:
        key_direction.x-=1
    if press_keys[K_RIGHT]:
        key_direction.x+=1
    if press_keys[K_UP]:
        key_direction.y-=1
    if press_keys[K_DOWN]:
        key_direction.y+=1
    # 向量规格化，求的单位向量
    key_direction.normalize()

    time_passed_second=clock.tick()/1000.

    screen.blit(bgimg,(0,0))
    screen.blit(sprite,sprite_pos.to_point())

    # 当前位置=原来位置+单位向量（方向）x 移动的距离（移动速度 x 移动时间）
    sprite_pos=sprite_pos+key_direction*sprite_speed*time_passed_second

    pygame.display.update()
